package net.kuratkoo.jidelnicekvut;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class DetailActivity extends ListActivity implements AdapterView.OnItemClickListener, AdapterView.OnCreateContextMenuListener {

    private static final String TAG = "JidelnicekVUT|DetailActivity";
    private TextView title;
    private Canteen canteen;
    private ProgressBar progress;
    private FoodSet foodSet;
    private LinearLayout loading;
    private TextView empty;
    private TextView address;
    private ImageView status;
    private TextView info;
    private LinearLayout footer;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_detail);
        Bundle extras = getIntent().getExtras();

        progress = (ProgressBar) findViewById(R.id.actionbar_progress);
        loading = (LinearLayout) findViewById(R.id.loading);
        empty = (TextView) findViewById(R.id.empty);
        title = (TextView) findViewById(R.id.title);
        address = (TextView) findViewById(R.id.address);
        status = (ImageView) findViewById(R.id.status);
        info = (TextView) findViewById(R.id.info);
        footer = (LinearLayout) findViewById(R.id.footer);

        this.getListView().setOnItemClickListener(this);
        this.registerForContextMenu(getListView());

        canteen = new Canteen(this);
        canteen.getByCanteenId(extras.getInt("canteenId"));

        title.setText(canteen.name);
        address.setText(canteen.address);
        info.setText(canteen.getFormatedOpeningInfo());
        if (canteen.isOpen()) {
            if (canteen.isCloseToClosing()) {
                status.setImageResource(android.R.drawable.presence_away);
                footer.setBackgroundResource(R.color.just_light_orange);
            } else {
                status.setImageResource(android.R.drawable.presence_online);
                footer.setBackgroundResource(R.color.just_light_green);
            }
        } else {
            status.setImageResource(android.R.drawable.presence_busy);
            footer.setBackgroundResource(R.color.just_light_red);
        }

        footer.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Builder ad = new AlertDialog.Builder(DetailActivity.this);
                ad.setTitle(canteen.name);
                ad.setMessage(canteen.getFormatedOpeningHours());
                ad.show();
            }
        });

        new RefreshAsyncTask().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu_detail, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.opening_hours:
                Builder ad = new AlertDialog.Builder(this);
                ad.setTitle(canteen.name);
                ad.setMessage(getText(R.string.opening_hours) + ":\n" + canteen.getFormatedOpeningHours());
                ad.show();
                return true;
            case R.id.preferences:
                startActivity(new Intent(this, Preferences.class));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderIcon(android.R.drawable.btn_star_big_on);
        menu.setHeaderTitle(this.foodSet.get(adapterContextMenuInfo.position).food);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu_food_list, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
        Integer score = 3;
        switch (item.getItemId()) {
            case R.id.voteUp:
                score = 5;
                break;
            case R.id.voteDown:
                score = 1;
                break;
            case R.id.vote:
                score = 3;
                break;
        }
        new VoteAsyncTask().execute(new Integer[]{adapterContextMenuInfo.position, score});
        return true;
    }

    private class VoteAsyncTask extends AsyncTask<Integer, Void, String> {
        @Override
        protected void onPreExecute() {
            progress.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(Integer... argv) {
            try {
                if (foodSet.get(argv[0]).vote(argv[1])) {
                    return "update";
                } else {
                    return "insert";
                }
            } catch (Exception ex) {
                Log.e(TAG, "Error: " + ex.getLocalizedMessage());
                return ex.getLocalizedMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            progress.setVisibility(View.GONE);
            if (result.equals("insert")) {
                Toast.makeText(DetailActivity.this, getText(R.string.vote_ok_insert), Toast.LENGTH_LONG).show();
                foodSet.sort();
                ((FoodListAdapter) getListAdapter()).notifyDataSetChanged();
            } else if (result.equals("update")) {
                Toast.makeText(DetailActivity.this, getText(R.string.vote_ok_update), Toast.LENGTH_LONG).show();
                foodSet.sort();
                ((FoodListAdapter) getListAdapter()).notifyDataSetChanged();
            } else {
                Toast.makeText(DetailActivity.this, getText(R.string.unable_to_vote), Toast.LENGTH_LONG).show();
            }
        }
    }

    public void goHome(View view) {
        startActivity(new Intent(DetailActivity.this, MainActivity.class));
    }

    public void goRefresh(View view) {
        new RefreshAsyncTask().execute();
    }

    public void onItemClick(AdapterView<?> adapterView, View v, int pos, long i) {
        Builder ad = new AlertDialog.Builder(this);
        ad.setTitle(foodSet.get(pos).food);
        ad.setIcon(android.R.drawable.ic_dialog_info);
        ad.setMessage(foodSet.get(pos).contents);
        ad.show();
    }

    private class RefreshAsyncTask extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected void onPreExecute() {
            progress.setVisibility(View.VISIBLE);
            loading.setVisibility(View.VISIBLE);
            getListView().setVisibility(View.GONE);
            empty.setVisibility(View.GONE);
        }

        @Override
        protected Boolean doInBackground(Void... v) {
            try {
                foodSet = new FoodSet(getBaseContext());
                foodSet.getByCanteenId(canteen.canteenId);
            } catch (Exception ex) {
                Log.e(TAG, "Error: " + ex.getLocalizedMessage());
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            progress.setVisibility(View.GONE);
            loading.setVisibility(View.GONE);
            if (result) {
                if (!foodSet.isEmpty()) {
                    getListView().setVisibility(View.VISIBLE);
                    foodSet.sort();
                    setListAdapter(new FoodListAdapter(DetailActivity.this, foodSet));
                } else {
                    empty.setVisibility(View.VISIBLE);
                }
            } else {
                Toast.makeText(DetailActivity.this, getString(R.string.unable_to_load_food_list), Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (foodSet != null) {
            foodSet.sort();
            if (getListAdapter() != null) {
                ((FoodListAdapter) getListAdapter()).notifyDataSetChanged();
            } else {
                setListAdapter(new FoodListAdapter(DetailActivity.this, foodSet));
            }
        }
    }
}
